﻿@implements IDisposable
@inject IPageProgressService PageProgressService
@inject NavigationManager Navigation

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(MauiProgram).Assembly"
            AdditionalAssemblies="@_defaultAssemblies">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <Login></Login>
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <Error404></Error404>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

@code {

    private string _requestUri = string.Empty;

    private readonly IList<Assembly> _defaultAssemblies = new List<Assembly>()
    {
        Assembly.Load("Admin.RazorLib"),
        Assembly.Load("BaseData.RazorLib"),
        Assembly.Load("DataServer.RazorLib"),
        Assembly.Load("Device.RazorLib"),
        Assembly.Load("Production.RazorLib")
    };

    protected override void OnInitialized()
    {
        base.OnInitialized();

        Navigation.LocationChanged += NavigationManager_LocationChanged;
    }

    private async void NavigationManager_LocationChanged(object? sender, LocationChangedEventArgs e)
    {
        if (!_requestUri.Equals(e.Location))
        {
            _requestUri = e.Location;
            if (PageProgressService != null) await PageProgressService.StartAsync();
        }
    }

    public void Dispose()
    {
        if (Navigation != null)
        {
            // Unsubscribe from the event when our component is disposed
            Navigation.LocationChanged -= NavigationManager_LocationChanged;
        }
    }
}
